"""
客户端:
    功能: 根据用户输入.发送请求,得到结果.
结构:
    一级界面: 注册 登录 退出
    二级界面: 
"""

from socket import *
from getpass import getpass
import sys
import hashlib


class Enums:
    """枚举及相关字段"""
    REGISTER = 'R'
    LOGIN = 'L'
    LOOK = 'Q'
    EXIT_ = 'E'
    HISTORY = 'H'
    RE = 1
    LOG = 2
    QU = 3
    ADDR = ("127.0.0.1", 18693)


class Main:
    """启动网络建立链接"""

    def __init__(self):
        self.__sockfd = socket()
        self.__sockfd.connect(Enums.ADDR)

    def __second_login(self, name):
        while True:
            print("""
                  ================查询================
                  1. 查单词     2. 历史记录     3. 注销
                  ====================================
                  """)
            try:
                cmd = int(input("请选择->: "))
            except KeyboardInterrupt:
                self.__sockfd.send(Enums.EXIT_.encode())
                sys.exit("二级正常退出.")
            except Exception:
                print("请输入数字!")
                continue
            if not cmd:
                print("请输入非空字符!")
                continue
            elif cmd == Enums.RE:
                self.__do_query(name)
            elif cmd == Enums.LOG:
                self.__do_log(name)
            elif cmd == Enums.QU:
                return

    def __do_log(self, name):
        """历史记录"""
        self.__sockfd.send(f"H {name}".encode())
        data = self.__sockfd.recv(128).decode()
        if data == 'ok':
            while True:
                data_ = self.__sockfd.recv(1024).decode()
                if data_ == '##':
                    break
                print(data_)
        else:
            print("还没有历史记录哦!")

    def __do_query(self, name):
        """单词查询"""
        while True:
            try:
                word = input("输入查询的单词,输入##表示退出:")
            except KeyboardInterrupt:
                self.__sockfd.send(Enums.EXIT_.encode())
                sys.exit("欢迎再次使用.")
            if word == '##':
                return
            elif not word:
                continue
            self.__sockfd.send(f"Q {name} {word}".encode())
            print(self.__sockfd.recv(2048).decode())

    def start(self):
        while True:
            print("""
                  =============欢迎=============
                  1. 注册     2. 登录     3. 退出
                  ==============================
                  """)
            try:
                cmd = int(input("请选择->: "))
            except KeyboardInterrupt:
                self.__sockfd.send(Enums.EXIT_.encode())
                sys.exit("正常退出.")
            except Exception:
                print("请输入数字!")
                continue
            if not cmd:
                print("请输入非空字符!")
                continue
            elif cmd == Enums.RE:
                # self.__sockfd.send(cmd.encode())
                self.__do_register()
            elif cmd == Enums.LOG:
                self.__do_login()
            elif cmd == Enums.QU:
                self.__sockfd.send(Enums.EXIT_.encode())
                print("欢迎再次使用...")
                return
            # elif cmd == Enums.EXIT_:
            #     print("服务器断开了链接!")
            #     return

    def __do_login(self):
        """登录"""
        while True:
            try:
                name = input("输入账号: ")
                passwd = getpass("输入密码: ")
            except KeyboardInterrupt:
                self.__sockfd.send(Enums.EXIT_.encode())
                sys.exit("正常退出..")
            self.__sockfd.send(
                f"L {name} {self.__encryption(name, passwd)}".encode())
            data = self.__sockfd.recv(128).decode()
            if data == 'ok':
                print("登录成功!")
                self.__second_login(name)  # 进入二级界面
                return
            else:
                print(data)
                continue

    def __do_register(self):
        """注册函数"""

        while True:
            try:
                name = input("输入账号: ")
                passwd = getpass("输入密码: ")
                passwd1 = getpass("再次输入密码: ")
            except KeyboardInterrupt:
                self.__sockfd.send(Enums.EXIT_.encode())
                sys.exit("正常退出...")
            if passwd != passwd1:
                print("两次密码不相同,请重新输入!")
                continue
            elif ' ' in name or ' ' in passwd:  # 有空格服务器那边不好解析
                print("用户名和密码不能有空格")
                continue
            self.__sockfd.send(
                f"R {name} {self.__encryption(name, passwd)}".encode())
            data = self.__sockfd.recv(128).decode()
            if data == 'ok':
                print("注册成功.")
                self.__second_login(name)  # 进入二级界面
            else:
                print(data)
                continue

            return

    def __encryption(self, name, passwd):
        hash = hashlib.md5(name.encode())  # 加盐
        hash.update(passwd.encode())  # 加密
        return hash.hexdigest()


if __name__ == "__main__":
    a = Main()
    a.start()
